const { src, dest, series, parallel, watch } = require("gulp");
const webserver = require("gulp-webserver");
const sass = require("gulp-sass");//使用sass
const concat = require("gulp-concat"); //把css合并到一个min.css中
const webpackStream = require("webpack-stream");//打包js
const proxy = require("http-proxy-middleware");//跨域数据请求 配置代理
var BScroll = require('better-scroll');//页面滚动


function copyHtml() {
    return src('./src/*.html')
        .pipe(dest('./dev/'))
}

function copyFonts() {
    return src('./src/style/fonts/*.*')
        .pipe(dest('./dev/style/fonts/'));
}
function copyLibs() {
    return src('./src/lib/*.js')
        .pipe(dest('./dev/js/lib/'))
}
function copyImages() {
    return src("./src/images/*.*")
        .pipe(dest("./dev/images/"))
}
function compileJs() {
    return webpackStream({
        mode: "development",
        devtool: 'source-map',//查看错误的时候显示源代码
        entry: { app: './src/app.js', detail: './src/detail.js' },//入口文件，只要与app.js相关的都会被编译到app.min.js文件里面
        output: {
            filename: "[name].min.js",
        },
        module: {
            rules: [
                {
                    test: /\js$/,//匹配文件
                    exclude: /(node_modules)/,//需要排除的文件
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env'],
                            plugins: ['@babel/plugin-transform-runtime']
                        }
                    }
                },
                {
                    test: /\.html$/,
                    loader: "string-loader"
                }
            ]
        }
    })
        .pipe(dest("./dev/js/"))
}
function compileCss() {
    return src('./src/style/*.scss')
        .pipe(sass().on('error', sass.logError))
        // .pipe(concat("app.min.css"))
        .pipe(dest("./dev/style/"))
}


function server() {
    return src('./dev/')
        .pipe(webserver({
            livereload: true,
            open: true,
            middleware: [
                proxy('/api', {//api 地址里面包含/api时，就会执行下面的代理，访问下面的target
                    target: 'https://m.lagou.com/',//http://localhost:8090/detail
                    changeOrigin: true,//是否允许跨域
                    pathRewrite: {//请求路径的重写
                        '^/api/': ''
                    }
                }),
                proxy('/info', {//api 地址里面包含/api时，就会执行下面的代理，访问下面的target
                    target: 'http://localhost:8090',
                    changeOrigin: true,//是否允许跨域
                })
            ]
        }))
}
function watchFile() {
    watch('./src/**/*.html', copyHtml);
    watch(['./src/**/*.js', './src/view/*.*'], compileJs);
    watch('./src/style/*.scss', compileCss);
}
exports.default = series(parallel(compileJs, copyHtml, copyFonts, copyLibs, copyImages, compileCss), server, watchFile);